<?php

/**
 * 客户跟进记录模型
 */

namespace app\model\customer;

use think\Model;
use think\facade\Db;

class CustomerTrace extends Model
{
    // 设置表名
    protected $name = 'customer_trace';
    
    // 设置主键
    protected $pk = 'id';
    
    // 设置自动写入时间戳
    protected $autoWriteTimestamp = true;
    
    // 设置时间字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    
    // 设置类型转换
    protected $type = [
        'follow_time' => 'integer',
        'next_time' => 'integer',
        'create_time' => 'integer',
        'update_time' => 'integer',
        'delete_time' => 'integer',
    ];
    
    /**
     * 关联用户模型
     */
    public function admin()
    {
        return $this->belongsTo('app\model\Admin', 'admin_id', 'id');
    }
    
    /**
     * 关联客户模型
     */
    public function customer()
    {
        return $this->belongsTo('app\model\Customer', 'cid', 'id');
    }
    
    /**
     * 获取客户的最近跟进记录
     * @param int $customerId 客户ID
     * @param int $limit 记录数量
     * @param array $field 查询字段
     * @return array 跟进记录列表
     */
    public function getLatestTracesByCustomerId($customerId, $limit = 5, $field = '*')
    {
        return $this->field($field)
            ->where('cid', $customerId)
            ->where('delete_time', '=', 0)
            ->order('create_time', 'desc')
            ->limit($limit)
            ->select()
            ->toArray();
    }
    
    /**
     * 获取多个客户的最近跟进记录
     * @param array $customerIds 客户ID数组
     * @param int $limitPerCustomer 每个客户的记录数量
     * @param array $field 查询字段
     * @return array 跟进记录列表
     */
    public function getLatestTracesByCustomerIds($customerIds, $limitPerCustomer = 1, $field = '*')
    {
        if (empty($customerIds)) {
            return [];
        }
        
        // 这里简化处理，实际可以使用子查询优化
        $result = [];
        foreach ($customerIds as $customerId) {
            $traces = $this->getLatestTracesByCustomerId($customerId, $limitPerCustomer, $field);
            if (!empty($traces)) {
                $result[$customerId] = $traces;
            }
        }
        
        return $result;
    }
}